//
//  ECPurchase.m
//  myPurchase
//
//  Created by ris on 10-4-23.   modify by jkl 13-1-24.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ECPurchase.h"
#import "JSONKit.h"

/******************************
 SKProduct extend
 *****************************/
@implementation SKProduct (LocalizedPrice)

- (NSString *)localizedPrice{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    [numberFormatter setLocale:self.priceLocale];
    NSString *formattedString = [numberFormatter stringFromNumber:self.price];
    [numberFormatter release];
    return formattedString;
}

@end

/***********************************
 ECPurchaseHTTPRequest
 ***********************************/
@implementation ECPurchaseHTTPRequest
@synthesize productIdentifier = _productIdentifier;

@end

/******************************
 ECPurchase
 ******************************/
@implementation ECPurchase
@synthesize productDelegate = _productDelegate;
@synthesize transactionDelegate =_transactionDelegate;
@synthesize verifyRecepitMode = _verifyRecepitMode;

SINGLETON_IMPLEMENTATION(ECPurchase);

#pragma mark - helo function
// add by jkl
- (NSString*) base64Encode:(NSData *)data
{
    static char base64EncodingTable[64] = {
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
        'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };
    int length = [data length];
    unsigned long ixtext, lentext;
    long ctremaining;
    unsigned char input[3], output[4];
    short i, charsonline = 0, ctcopy;
    const unsigned char *raw;
    NSMutableString *result;
    
    lentext = [data length];
    if (lentext < 1)
        return @"";
    result = [NSMutableString stringWithCapacity: lentext];
    raw = [data bytes];
    ixtext = 0;
    
    while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0)
            break;
        for (i = 0; i < 3; i++) {
            unsigned long ix = ixtext + i;
            if (ix < lentext)
                input[i] = raw[ix];
            else
                input[i] = 0;
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
            case 1:
                ctcopy = 2;
                break;
            case 2:
                ctcopy = 3;
                break;
        }
        
        for (i = 0; i < ctcopy; i++)
            [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
        
        for (i = ctcopy; i < 4; i++)
            [result appendString: @"="];
        
        ixtext += 3;
        charsonline += 4;
        
        if ((length > 0) && (charsonline >= length))
            charsonline = 0;
    }
    return result;
}
// end add

#pragma mark - init
//you can init the object here as the object init is in SINGLETON_IMPLEMENTATION
-(void)postInit
{
	_verifyRecepitMode = ECVerifyRecepitModeNone;
	[self registerNotifications];
}

- (void)requestProductData:(NSArray *)proIdentifiers{
	NSSet *sets = [NSSet setWithArray:proIdentifiers];
    _productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:sets];
    _productsRequest.delegate = self;
    [_productsRequest start];
}

#pragma mark -
#pragma mark SKProductsRequestDelegate methods
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSArray *products = response.products;
#ifdef ECPURCHASE_TEST_MODE	
	NSMutableString *result = [[NSMutableString alloc] init];
	for (int i = 0; i < [products count]; ++i) {
		SKProduct *proUpgradeProduct = [products objectAtIndex:i];
		[result appendFormat:@"%@,%@,%@,%@\n",
		 proUpgradeProduct.localizedTitle,proUpgradeProduct.localizedDescription,proUpgradeProduct.price,proUpgradeProduct.productIdentifier];
	}
    
    for (NSString *invalidProductId in response.invalidProductIdentifiers)
    {
		[result appendFormat:@"Invalid product id: %@",invalidProductId];
    } 
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iap" message:result
										delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
	[_productDelegate didReceivedProducts:products];
#else
	[_productDelegate didReceivedProducts:products];

#endif   
	[_productsRequest release];
}

-(void)addTransactionObserver{
	_storeObserver = [[ECStoreObserver alloc] init];
	[[SKPaymentQueue defaultQueue] addTransactionObserver:_storeObserver];
}

-(void)removeTransactionObserver{
	[[SKPaymentQueue defaultQueue] removeTransactionObserver:_storeObserver];
}

-(void)addPayment:(NSString *)productIdentifier{
	SKPayment *payment = [SKPayment paymentWithProductIdentifier:productIdentifier];
	[[SKPaymentQueue defaultQueue] addPayment:payment];
}

//add by jkl
- (void)addPaymentWithProduct:(SKProduct *)product
{
    if (product) {
        SKPayment *payment = [SKPayment paymentWithProduct:product];
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

- (void)restoreCompletedPayment
{
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (NSString *)getReceiptFromProductID:(NSString *)productID
{
    if (!productID) {
        return nil;
    }
    NSMutableArray *completedTransArray = [self getCompleteTrans];
    for (SKPaymentTransaction *transaction in completedTransArray) {
        if (transaction) {
            if ([productID isEqualToString:transaction.payment.productIdentifier]) {
                return [self base64Encode:transaction.transactionReceipt];
            }
        }
    }
    return nil;
}
//end add

#pragma mark -
#pragma mark NSNotificationCenter Methods
-(void)completeTransaction:(NSNotification *)note{
	SKPaymentTransaction *trans = [[note userInfo] objectForKey:@"transaction"];
	if (_verifyRecepitMode == ECVerifyRecepitModeNone) {
		[_transactionDelegate didCompleteTransaction:trans.payment.productIdentifier];
	}
	else if(_verifyRecepitMode == ECVerifyRecepitModeiPhone){
		[self verifyReceipt:trans];
	}
	else if(_verifyRecepitMode == ECVerifyRecepitModeServer){
		[self verifyReceipt:trans];
	}else if(_verifyRecepitMode == ECVerifyRecepitModeCustomServer){  // add by jkl
        NSString *recepit = [self base64Encode:trans.transactionReceipt];
        [_transactionDelegate didCompleteTransaction:trans.payment.productIdentifier withReceipt:recepit];
    }
    // end add
}

-(void)failedTransaction:(NSNotification *)note{
	SKPaymentTransaction *trans = [[note userInfo] objectForKey:@"transaction"];
	[_transactionDelegate didFailedTransaction:trans.payment.productIdentifier error:trans.error];
}

-(void)restoreTransaction:(NSNotification *)note{
	SKPaymentTransaction *trans = [[note userInfo] objectForKey:@"transaction"];
    if (_verifyRecepitMode == ECVerifyRecepitModeNone) {
        [_transactionDelegate didRestoreTransaction:trans.payment.productIdentifier];
	}
	else if(_verifyRecepitMode == ECVerifyRecepitModeiPhone){
		[self verifyReceipt:trans];
	}
	else if(_verifyRecepitMode == ECVerifyRecepitModeServer){
		[self verifyReceipt:trans];
	}else if(_verifyRecepitMode == ECVerifyRecepitModeCustomServer){  // add by jkl
        NSString *recepit = [self base64Encode:trans.transactionReceipt];
        [_transactionDelegate didCompleteTransaction:trans.payment.productIdentifier withReceipt:recepit];
    }
}

- (void)restoreTransactionFailed:(NSNotification *)note
{
    NSError *error = [[note userInfo] objectForKey:@"error"];
    [_transactionDelegate didFailedRestoreTransaction:error];
}

-(void)registerNotifications{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(completeTransaction:) name:@"completeTransaction" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(failedTransaction:) name:@"failedTransaction" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restoreTransaction:) name:@"restoreTransaction" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(restoreTransactionFailed:) name:@"restoreTransactionFailed" object:nil];
}

-(void)verifyReceipt:(SKPaymentTransaction *)transaction
{
	_networkQueue = [ASINetworkQueue queue];
	[_networkQueue retain];
	NSURL *verifyURL = [NSURL URLWithString:VAILDATING_RECEIPTS_URL];
	ECPurchaseHTTPRequest *request = [[ECPurchaseHTTPRequest alloc] initWithURL:verifyURL];
	[request setProductIdentifier:transaction.payment.productIdentifier];
	[request setRequestMethod: @"POST"];
	[request setDelegate:self];
	[request setDidFinishSelector:@selector(didFinishVerify:)];
	//[request setShouldRedirect: NO];
	[request addRequestHeader: @"Content-Type" value: @"application/json"];
	
	//NSString *recepit = [[NSString alloc] initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
	NSString *recepit = [self base64Encode:transaction.transactionReceipt];
	//NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
//																				   NULL,
//																				   (CFStringRef)recepit,
//																				   NULL,
//																				   (CFStringRef)@"!*'();:@&=+$,/?%#[]",
//																				   kCFStringEncodingUTF8 );
//	NSString * encodedString =  [recepit stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    // modify by jkl
	NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys:recepit, @"receipt-data", nil];
    NSString *jsonStr = [data JSONString];
	[request appendPostData: [jsonStr dataUsingEncoding: NSUTF8StringEncoding]];
    // end modify
	[_networkQueue addOperation: request];
	[_networkQueue go];
}

// end add
-(void)didFinishVerify:(ECPurchaseHTTPRequest *)request
{
	NSString *response = [request responseString];
    // modify by jkl
    NSDictionary *jsonData = [response objectFromJSONString];
    if (jsonData && [jsonData isKindOfClass:[NSDictionary class]]) {
    // end modify
        NSNumber *status = [jsonData objectForKey: @"status"];
        if ([status intValue] == 0) {
            NSDictionary *receipt = [jsonData objectForKey: @"receipt"];
            NSString *productIdentifier = [receipt objectForKey: @"product_id"];
            [_transactionDelegate didCompleteTransactionAndVerifySucceed:productIdentifier];
        }
        else {
//            NSString *exception = [jsonData objectForKey: @"exception"];
            NSString *exception = @"verifyFailed!";
            [_transactionDelegate didCompleteTransactionAndVerifyFailed:request.productIdentifier withError:exception];
        }
    }else{
        // 解析返回的request错误
        KNSLOG(@"request parse error!");
    }
}

#pragma mark -
#pragma mark Get Property From ECStoreObserver
-(NSMutableArray *)getCompleteTrans{
	return _storeObserver.completeTrans;
}

-(NSMutableArray *)getRestoreTrans{
	return _storeObserver.restoreTrans;
}

-(NSMutableArray *)getFailedTrans{
	return _storeObserver.failedTrans;
}

-(void)dealloc
{
	RELEASE_SAFELY(_networkQueue);
	RELEASE_SAFELY(_storeObserver);
	[super dealloc];
}

@end